package com.taobao.taokeeper.monitor.core;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.taobao.common.toolkit.exception.DaoException;
import com.taobao.common.toolkit.util.ThreadUtil;
import com.taobao.taokeeper.common.GlobalInstance;
import com.taobao.taokeeper.dao.TaoKeeperSettingsDAO;
import com.taobao.taokeeper.model.TaoKeeperSettings;
import com.taobao.taokeeper.monitor.core.task.ZooKeeperALiveCheckerJob;
import com.taobao.taokeeper.monitor.core.task.ZooKeeperStatusCollectJob;
import com.taobao.taokeeper.monitor.task.job.HostPerformanceCollectJob;
import com.taobao.taokeeper.monitor.task.job.ZooKeeperClientThroughputStatJob;
import com.taobao.taokeeper.monitor.task.job.ZooKeeperClusterMapDumpJob;

/**
 * Description: 初始化系统。包括以下工作:<br>
 * 1.从数据库加载系统配置 2.启动各个JOB
 * 
 * @author yinshi.nc
 * @Date 2011-10-27
 */
public class Initialization extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger( Initialization.class );

	public void init() {

		/** Init threadpool */
		ThreadPoolManager.init();

		initSystem();

		// 启动ZooKeeper 集群信息 DUMP 任务
		Thread zooKeeperClusterMapDumpJobThread = new Thread( new ZooKeeperClusterMapDumpJob() );
		zooKeeperClusterMapDumpJobThread.start();
		try {
			// 这里等待一下，因为第一次一定要dump成功，
			// TODO 这个等待逻辑要改。
			Thread.sleep( 5000 );
		} catch ( InterruptedException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/** 启动zookeeper流量统计任务 */
		ThreadUtil.startThread( new ZooKeeperClientThroughputStatJob() );

		/** 启动ZooKeeper数据修改通知检测 */
		ThreadUtil.startThread( new ZooKeeperALiveCheckerJob() );

		/** 启动ZooKeeper集群状态收集 */
		ThreadUtil.startThread( new ZooKeeperStatusCollectJob() );

		/** 收集机器CPU LOAD MEMEORY */
		ThreadUtil.startThread( new HostPerformanceCollectJob() );

		LOG.info( "所有任务顺利启动" );
	}

	/**
	 * 从数据库加载并初始化系统配置
	 */
	private void initSystem() {

		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
		TaoKeeperSettingsDAO taoKeeperSettingsDAO = ( TaoKeeperSettingsDAO ) wac.getBean( "taoKeeperSettingsDAO" );

		TaoKeeperSettings taoKeeperSettings = null;
		try {
			taoKeeperSettings = taoKeeperSettingsDAO.getTaoKeeperSettingsBySettingsId( 1 );
		} catch ( DaoException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if ( null != taoKeeperSettings )
			GlobalInstance.taoKeeperSettings = taoKeeperSettings;
	}

}
